package servlet;

import java.io.IOException;
import java.sql.Connection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.DataBase;
import model.EventFieldsCondition;
import model.EventType;
import model.Field;
import model.Table;
import model.User;
import model.UserEvent;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import service.EventFieldConditionService;
import utils.JdbcUtil;
import utils.RequestUtil;
import utils.ResponseUtil;
import utils.ResultOfInsert;
import dao.DataBaseDao;
import dao.EventFieldsConditionDao;
import dao.EventTypeDao;
import dao.FieldDao;
import dao.NoiseDao;
import dao.TableDao;
import dao.UserDao;
import dao.UserEventDao;


/**
 * 定制预警
 */
@WebServlet(description = "CustomServlet", urlPatterns = { "/CustomServlet" })
public class CustomServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
	JdbcUtil dbUtil=new JdbcUtil();
	DataBaseDao dbDao = new DataBaseDao();
	TableDao tDao = new TableDao();
	FieldDao fDao = new FieldDao();
	EventTypeDao etDao = new EventTypeDao();
	UserDao uDao = new UserDao();
	UserEventDao ueDao = new UserEventDao();
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String method = RequestUtil.get(request.getParameter("method"));
		if(method.equals("getDBs")) {
			getDBs(request, response);
		} else if(method.equals("getTables")) {
			getTables(request, response);
		} else if(method.equals("getFields")) {
			getFields(request, response);
		} else if(method.equals("getEventTypes")) {
			getEventTypes(request, response);
		} else if(method.equals("checkUser")) {
			checkUser(request, response);
		} else if(method.equals("custom")) {
			//custom(request, response);
			customWithTransaction(request, response);
		} else if(method.equals("getLocationValue")){
			getLocationValue(request,response);
		}else if(method.equals("getUserPhone")){
			getUserPhone(request,response);
		}
	}



	/**
	 * 注册事件，注册事件的时候要插入往UserEvent表中插入一条记录，同时往t_eventFieldsCondition分别插入至少两个符合条件的字段，待监控字段与位置字段
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void custom(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		System.out.println("..........注册事件.................");
		
//		String message = (String) request.getSession().getAttribute("ok");
//		System.out.println(message);
//		if(message == null || !message.equals("1")) {
//			request.getRequestDispatcher("/error.jsp")
//			.forward(request, response);
//			return;
//		}
		JSONObject result = new JSONObject();
		String phone = RequestUtil.get(request.getParameter("phone"));
		String etIdString = RequestUtil.get(request.getParameter("et"));
		String pollingTimeString = RequestUtil.get(request.getParameter("time"));
		String timeSpanString = RequestUtil.get(request.getParameter("span"));
		String fIdString = RequestUtil.get(request.getParameter("fields"));
		String tIdString = RequestUtil.get(request.getParameter("tables"));
		String valueString = RequestUtil.get(request.getParameter("value"));
		String condition = RequestUtil.get(request.getParameter("condition"));
		String locationFields =  RequestUtil.get(request.getParameter("locationFields"));
		String locationValue = RequestUtil.get(request.getParameter("locationValue"));
		String desc = RequestUtil.get(request.getParameter("desc"));
		String type = RequestUtil.get(request.getParameter("type"));
		UserEvent ue = null;
		
		int count = 0;//插入成功与否的标志
		//这里没有考虑事务问题
		User user = uDao.getUser(phone);
		if(user!=null){
			Date currentTime = new Date();
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String dateString = formatter.format(currentTime);
			ue = new UserEvent(user.getId(), Integer.parseInt(etIdString),Integer.parseInt(tIdString), Integer.parseInt(pollingTimeString)*1000,Integer.parseInt(timeSpanString)*1000, dateString,desc,type);
			ResultOfInsert roi = ueDao.save(ue);
			if (roi.getCount()!=0) {
				EventFieldsConditionDao efcDao = new EventFieldsConditionDao();
				EventFieldsCondition efc = null;
				efc = new EventFieldsCondition(Integer.parseInt(fIdString), roi.getId(), condition, valueString);
				int rsAddMonitor = efcDao.save(efc);//rsAddMonitor，添加条件:待监控字段
				
				EventFieldsCondition efcLocation = null;
				efcLocation = new EventFieldsCondition(Integer.parseInt(locationFields),roi.getId(),"=",locationValue);
				int rsAddLocation = efcDao.save(efcLocation); //添加条件：位置字段
				count = 1;
			}
		}
		result.put("result", count);
		try {
			ResponseUtil.write(result, response);
		} catch (Exception e) {
			e.printStackTrace();
		}	
				
	}
	/**
	 * custom函数的考虑事务版本
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void customWithTransaction(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		System.out.println("..........注册事件，考虑事务.................");
		

		JSONObject result = new JSONObject();
		String phone = RequestUtil.get(request.getParameter("phone"));
		String etIdString = RequestUtil.get(request.getParameter("et"));
		String pollingTimeString = RequestUtil.get(request.getParameter("time"));
		String timeSpanString = RequestUtil.get(request.getParameter("span"));
		String fIdString = RequestUtil.get(request.getParameter("fields"));
		String tIdString = RequestUtil.get(request.getParameter("tables"));
		String valueString = RequestUtil.get(request.getParameter("value"));
		String condition = RequestUtil.get(request.getParameter("condition"));
		String locationFields =  RequestUtil.get(request.getParameter("locationFields"));
		String locationValue = RequestUtil.get(request.getParameter("locationValue"));
		String desc = RequestUtil.get(request.getParameter("desc"));
		String type = RequestUtil.get(request.getParameter("type"));
		UserEvent ue = null;
		
		int count = 0;//插入成功与否的标志
		//这里没有考虑事务问题
		User user = uDao.getUser(phone);
		if(user!=null){
			Date currentTime = new Date();
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String dateString = formatter.format(currentTime);
			ue = new UserEvent(user.getId(), Integer.parseInt(etIdString),Integer.parseInt(tIdString), Integer.parseInt(pollingTimeString)*1000,Integer.parseInt(timeSpanString)*1000, dateString,desc,type);
			
			////添加条件：待监控字段
			EventFieldsCondition efc = null;
			efc = new EventFieldsCondition(Integer.parseInt(fIdString), -1, condition, valueString);//第2个参数暂时设置为-1，仅仅起到占位作用
			
			//添加条件：位置字段
			EventFieldsCondition efcLocation = null;
			efcLocation = new EventFieldsCondition(Integer.parseInt(locationFields),-1,"=",locationValue);//第2个参数暂时设置为-1，仅仅起到占位作用
			
			count = EventFieldConditionService.register(ue, efc,efcLocation);
		}
		result.put("result", count);
		try {
			ResponseUtil.write(result, response);
		} catch (Exception e) {
			e.printStackTrace();
		}	
				
	}
	

	private void checkUser(HttpServletRequest request,
			HttpServletResponse response) {
		String phone = RequestUtil.get(request.getParameter("phone"));
		HttpSession session = request.getSession();
		//session.removeAttribute("ok");
		System.out.println("检查前：" + session.getAttribute("ok"));
		JSONObject result = new JSONObject();
		User user = uDao.getUser(phone);
		if(user != null) {
//				Cookie message = new Cookie("message", "true");
//				response.addCookie(message);
			result.put("exist", "1");
			session.setAttribute("ok", "1");
		} else {
//				Cookie message = new Cookie("message", "false");
//				response.addCookie(message);
			result.put("exist", "0");
			session.setAttribute("ok", "0");
		}
		System.out.println("检查后：" + session.getAttribute("ok"));
		
		try {
			ResponseUtil.write(result, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	private void getEventTypes(HttpServletRequest request,
			HttpServletResponse response) {
		response.setContentType("text/html;charset=utf-8");
		List<EventType> etList = etDao.getEventTypeList();
		String json = JSONArray.fromObject(etList).toString();
	    try {
			response.getWriter().write(json);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void getFields(HttpServletRequest request,
			HttpServletResponse response) {
		String tId = RequestUtil.get(request.getParameter("tId"));
		String fieldType=RequestUtil.get(request.getParameter("fieldType"));
		List<Field> fieldList = fDao.getFieldListbyTidAndType(tId, fieldType);
		String json = JSONArray.fromObject(fieldList).toString();
	    try {
			response.getWriter().write(json);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

	private void getTables(HttpServletRequest request, HttpServletResponse response) {
		String dbId = RequestUtil.get(request.getParameter("dbId"));
		List<Table> tableList = tDao.getTableList(dbId);
		String json = JSONArray.fromObject(tableList).toString();
		try {
			response.getWriter().write(json);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

	private void getDBs(HttpServletRequest request, HttpServletResponse response) {
	
		List<DataBase> dbList = dbDao.getDBList();
		String json = JSONArray.fromObject(dbList).toString();
		response.setContentType("text/html;charset=utf-8");//解决中文乱码问题
	    try {
			response.getWriter().write(json);
		} catch (IOException e) {
			e.printStackTrace();
		}
	   
	}
	
	 private void getLocationValue(HttpServletRequest request,HttpServletResponse response){
		 String field = request.getParameter("field");
		 String dbName = request.getParameter("dbName");
		 String tbName = request.getParameter("tbName");
		 List<DataBase> dbList = new ArrayList<DataBase>();
		 dbList = dbDao.getDBListbyName(dbName);
		 DataBase db = dbList.get(0);

		 NoiseDao nd= new NoiseDao();
		 List<String> locationList = nd.getLocations(db,tbName,field);
			String json = JSONArray.fromObject(locationList).toString();
			response.setContentType("text/html;charset=utf-8");//解决中文乱码问题
		    try {
				response.getWriter().write(json);
			} catch (IOException e) {
				e.printStackTrace();
			}
	    }
	 
	 
		private void getUserPhone(HttpServletRequest request, HttpServletResponse response) {
			// TODO Auto-generated method stub
			List<User> UserList = uDao.getUserInfo();
			String json = JSONArray.fromObject(UserList).toString();
			try {
				response.getWriter().write(json);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}


}
